package com.example.servlet.response;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-02 14:26
 **/
@WebServlet("/response8")
public class ResponseDemo8 extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ServletContext context = getServletContext();
        //获取文件路径
        String filename = req.getParameter("filename");
        String path = context.getRealPath("/download/" + filename);
        System.out.println("真是路径: " + path);
        //获取文件
        File file = new File(path);
        //注意: 需要先设置头,再读取流,不然文件可能会在浏览器打开,设置头失效
        //响应中写入流文件类型,MimeType
        // String mimeType = context.getMimeType(filename);
        // resp.setContentType(mimeType);
        //application/octet-stream
        resp.setHeader("Content-Type", "application/octet-stream");
        //    文件名写入
        resp.setHeader("Content-Disposition", "attachment;filename=" + filename);

        if (file.exists()) {

            //生成输入流
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                 ServletOutputStream os = resp.getOutputStream();) {

                byte[] bytes = new byte[1024];
                int len;

                //生成输入流

                while ((len = bis.read(bytes)) != -1) {
                    os.write(bytes, 0, len);
                }
                //关闭输入流 try 关闭了

            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }

        }

    }
}
